package com.net.xpay.web.controller.merchant;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.domain.TaokeDetectionBatch;
import com.net.xpay.core.domain.TaokeDetectionRecord;
import com.net.xpay.core.manager.TaokeDetectionBatchManager;
import com.net.xpay.core.manager.TaokeDetectionRecordManager;
import com.net.xpay.core.model.TaokeDetectionModel;
import com.net.xpay.core.model.TaokeDetectionRecordSearchModel;
import com.net.xpay.core.service.TaokeDetectionService;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2020/5/7 13:31

 */
@RestController
@Slf4j
@RequestMapping("/merchant/taoke-detection-record")
@Api(tags = "商户/淘客单检测", description = "商户 淘客单检测 net")
public class TaokeDetectionRecordController {

    @Autowired
    private TaokeDetectionService taokeDetectionService;

    @Autowired
    private TaokeDetectionRecordManager taokeDetectionRecordManager;

    @Autowired
    private TaokeDetectionBatchManager taokeDetectionBatchManager;

    /**
     * 单笔订单检测
     */
    @ApiOperation("单笔订单检测")
    @PostMapping("/detection")
    public ResultData<TaokeDetectionRecord> detection(@ApiIgnore @RequestUser User merchant, @RequestBody TaokeDetectionModel detectionModel) {
        Preconditions.checkArgument(detectionModel != null);
        return new ResultData<>(taokeDetectionService.detection(merchant, detectionModel));
    }

    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    public ResultPagedList<TaokeDetectionRecord> search(@ApiIgnore @RequestUser User merchant, @RequestBody TaokeDetectionRecordSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());
        List<TaokeDetectionRecord> records = taokeDetectionRecordManager.search(searchModel);
        long count = taokeDetectionRecordManager.searchCount(searchModel);

        return new ResultPagedList<>(records, count, searchModel);
    }

    /**
     * 导出淘客检测明细
     */
    @ApiOperation("导出淘客检测明细")
    @GetMapping("/export")
    public ResultData<Boolean> exportTaokeDetectionRecord(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, Long batchId) {
        Preconditions.checkArgument(batchId != null);

        TaokeDetectionBatch batch = taokeDetectionBatchManager.findById(merchant.getId(), batchId);
        List<TaokeDetectionRecord> records = taokeDetectionRecordManager.listByBatchId(merchant.getId(), batchId);

        Map<String, Object> model = new HashMap<>();
        model.put("records", records);
        model.put("batch", batch);

        String fileName = "批量查淘客下单明细(" + batchId + ").xlsx";
        String template = "/excel/tpl/批量查淘客下单明细.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }


}
